<?php
namespace app\api\controller;

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;
use Imagick;

class Pword
{
private $_save_path;
public function __construct($params=array())
{
    if(!empty($params['save_path'])){
        $this->_save_path = $params['save_path'];
    }
}
public function generateWordByTemplate($template_path,$params){
    try{
        $phpWord = new PhpWord();
        $document = new TemplateProcessor($template_path);
        foreach($params as $key => $value){
            if($key=="workName"||$key=="img"){
                continue;
            }
            $document->setValue($key,$value);
        }
        $document->saveAs($this->_save_path);
        sleep(2);
        $pathArr = explode("contract",$this->_save_path);
        $pdfPath =  $pathArr[0]."contract";
        $e = "soffice --headless --convert-to pdf ".$this->_save_path." --outdir " .$pdfPath;
        $s = shell_exec($e);
        sleep(1);
        $fielNameArr = explode(".",$pathArr[1]);
        $imageFile = $pathArr[0]."contract".$fielNameArr[0].".jpg";
        $pdfFile = $pdfPath.$fielNameArr[0].".pdf";
        // gs -sDEVICE=jpeg -sOutputFile=output.jpg -r300x300 -dPDFFitPage -dBATCH -dNOPAUSE -q input.png
        $command = "gs -sDEVICE=jpeg -o {$imageFile} -r300 -dPDFFitPage {$pdfFile}";
        exec($command,$outImgs, $returnVar); 
        if ($returnVar === 0) {
            echo "转换成功";
        } else {
            echo "转换失败";
        }
        return $imageFile;
    }
    catch(\Exception $e){
        throw new \Exception($e->getMessage());
    }
}

}